<template>
	<view>
		<!-- <u-navbar :is-back="true" :is-fixed="true" title="公用品牌码"></u-navbar> -->
		<scroll-view scroll-y scroll-with-animation style="height: calc(100vh - 60px);" :show-scrollbar="false">
			<free-divider></free-divider>
			<!-- 审核通过不显示 是待审核-->
			<view class="py-5" v-if="ScanCode.approvalState === 'approval'">
				<u-steps :list="numList" :current="1" mode="number" active-color="#FFC251"
					un-active-color="#FFC251"></u-steps>
				<view class="text-999999 mt-5 pr-3 pl-7">未通过原因：{{ScanCode.remark}}</view>
			</view>
			<!-- 审核通过不显示 拒绝-->
			<view class="py-5" v-if=" ScanCode.approvalState ==='reject'">
				<u-steps :list="numLists" :current="1" mode="number" active-color="#FFC251"
					un-active-color="#BD3124"></u-steps>
				<view class="text-999999 mt-5 pr-3 pl-7">未通过原因：{{ScanCode.remark}}</view>
			</view>
			<!-- 审核通过不显示 成功-->
			<view class="py-5" v-if=" ScanCode.approvalState ==='success'">
				<u-steps :list="numLista" :current="1" mode="number" active-color="#FFC251"
					un-active-color="#78AB06"></u-steps>
				<view class="text-999999 mt-5 pr-3 pl-7">通过原因：{{ScanCode.remark}}</view>
			</view>
			<!-- 判断显示 -->
			<view style=" background-color:#EFEDE9;">
				<view v-if="ScanCode.approvalState === null" class="pl-2 pr-2 font-14 lineHight-40">您还未申请品牌码，请填写品牌码申请表
				</view>
				<view v-if="ScanCode.approvalState === 'approval'" class="pl-2 pr-2 font-14 lineHight-40">品牌码申请信息</view>
			</view>
			<!-- 审核通过显示  success-->

			<view v-if="ScanCode.state === 'success'" class="py-5"
				style="display: flex; flex-direction: column; align-items: center;">

				<uqrcode ref="uqrcode" canvas-id="qrcode" :value="ScanCode.id" size="150" :options="{ }"
					:h5SaveIsDownload="true" :h5DownloadName="newList.enterpriseName"></uqrcode>

				<view class="py-3">{{ScanCode.publicBrandName}} 
					<text class="ml-3 text-8ED0F2" v-if="ScanCode.approvalState ==='success'" @click="downloadQR">下载</text> 
				</view>
			</view>
			<view v-if="ScanCode.state === 'success' && ScanCode.approvalState !== 'approval' && ScanCode.approvalState !== 'reject'"
				style="background-color:#EFEDE9;" class="dfex pl-2 pr-2 font-14 lineHight-40">
				<view>品牌码信息</view>
				<view v-if="userInfo.parentId === null" class="text-8ED0F2" @click="editAndSave">编辑</view>
			</view>

			<u-form :model="form">
				<u-form-item :label-style="labelStyle" label="企业名称" prop="name">
					<u-input class="mr-3" :disabled="true" v-model="newList.enterpriseName" input-align="right" />
				</u-form-item>
				
				
				<u-form-item v-if="ScanCode.approvalState === null" :label-style="labelStyle" label="公用品牌名称"
					prop="name">
					<u-input class="mr-3 " v-model="form.publicBrandName" input-align="right" />
				</u-form-item>
				<u-form-item v-else-if="ScanCode.approvalState === 'reject'" :label-style="labelStyle" label="公用品牌名称" prop="name">
					<u-input class="mr-3 " v-model="form.publicBrandName ||  ScanCode.publicBrandName"
						 input-align="right" />
				</u-form-item>
				<u-form-item v-else :label-style="labelStyle" label="公用品牌名称" prop="name">
					<u-input class="mr-3 " v-model="form.publicBrandName ||  ScanCode.publicBrandName"
						:disabled="!publicBrandNameEditable" input-align="right" />
				</u-form-item>
				
				
				<u-form-item :label-style="labelStyle" label="统一社会信用代码" prop="name">
					<u-input class="mr-3 " :disabled="true" v-model="newList.unifiedCreditCode" input-align="right" />
				</u-form-item>
				<u-form-item v-if="ScanCode.approvalState === null" style="padding-right: 10px;"
					:label-style="labelStyle" label="产品名称" prop="name">
					<u-input v-model="valueProductName" placeholder="请选择" :type="type" input-align="right"
						:border="false" @click="showNatureBusinessHandler" />
					<!-- <u-action-sheet :list="actionListCp" v-model="showProductName"
						@click="actionClickProductName"></u-action-sheet> -->
					<u-picker @confirm="selectNatureBusiness" mode="selector" v-model="showNatureBusiness"
						:default-selector="[0]" :range="natureBusinessList" range-key="text"></u-picker>
				</u-form-item>
				<view v-else>
					<view v-if="!showFerrButton && ScanCode.approvalState !== 'reject'" class="border-EFEFEF">
						<view class="dfex pl-3 pr-3 lineHight-40">
							<view>产品名称</view>
							<view>{{ScanCode.productsName}}</view>
						</view>
					</view>
					<u-form-item v-if="showFerrButton || ScanCode.approvalState === 'reject'" style="padding-right: 10px;" :label-style="labelStyle"
						label="产品名称" prop="name">
						<u-input v-model="valueProductName || ScanCode.productsName" :disabled="!productsNameEditable"
							placeholder="请选择" :type="type" input-align="right" :border="false"
							@click="showNatureBusinessHandler" />
						<!-- <u-action-sheet :list="actionListCp" v-model="showProductName"
							@click="actionClickProductName"></u-action-sheet> -->
						<u-picker @confirm="selectNatureBusiness" mode="selector" v-model="showNatureBusiness"
							:default-selector="[0]" :range="natureBusinessList" range-key="text"></u-picker>
					</u-form-item>
				</view>

			</u-form>
			<view v-if="showFerrButton  || ScanCode.approvalState === 'reject' || ScanCode.approvalState !== 'approval' && ScanCode.approvalState !=='success'" class="dfex pl-3 pr-3 mt-3">
				<view>
					<text class="text-FF0000">*</text>
					<text>准入证书</text>
				</view>
				<u-upload ref="uUpload" :file-list="fileList" :max-size="4 * 1024 * 1024" :form-data="{'biz':'temp'}"
					:header="header" @on-success="uploadSuccess" :action="getUploadUrl()" max-count="1"></u-upload>
				<view class="font-12 text-999999 pl-1">图片限制不能超过4MB</view>

			</view>
			<view v-if="!showFerrButton && !showFerr && ScanCode.approvalState !== 'reject' || ScanCode.approvalState === 'approval'" class="dfex pl-3 pr-3 mt-3">
				<view>
					<text class="text-FF0000">*</text>
					<text>准入证书</text>
				</view>
				<view>
					<img style="width: 120px; height: 120px; border-radius: 5px;"
						:src="getFullImageUrl(iamg_tup)"></img>
				</view>
			</view>

			<!-- 判断提交 -->
			<ferrButton v-if="ScanCode.approvalState === null" title="提交申请" @click="SubmitApplication"></ferrButton>
			<!-- 判断重新提交 -->
			<ferrButton v-if="ScanCode.approvalState === 'reject'" title="重新提交" @click="SubmitAnewAdd"></ferrButton>
			<!-- 编辑 -->
			<ferrButton v-if="showFerrButton" title="保存" @click="SubmitEdit"></ferrButton>


		</scroll-view>
	</view>
</template>

<script>
	import $H from '@/common/free-lib/request.js';
	import $U from "@/common/free-lib/util.js";
	import freeAvater from "@/components/free-ui/free-avater.vue";
	import freeDivider from "@/components/free-ui/free-divider.vue";
	import ferrButton from "@/components/free-ui/ferr-button.vue";
	import {
		getImageUrl
	} from '@/common/free-lib/util.js';
	export default {
		components: {
			freeAvater,
			freeDivider,
			ferrButton,
		},
		data() {
			return {
				form: {
					publicBrandName: '',
					id: '',
					productsNameId: '',
					admissionCertificate: ''
				},
				newList: {},
				ultureList: {},
				labelStyle: {
					paddingLeft: '13px',
					width: '130px'
				},
				type: 'select',
				selectedNameDate: null,
				actionListCp: [], // 产品名称列表
				showProductName: false, // 控制显示产品名称选项的变量
				valueProductName: '', // 选中的产品名称值
				showFerr:false,
				border: true,
				numList: [{
					name: '提交申请'
				}, {
					name: '审批中'
				}, {
					name: '待审核'
				}],
				numLists: [{
					name: '提交申请'
				}, {
					name: '审批中'
				}, {
					name: '拒绝'
				}],
				numLista: [{
					name: '提交申请'
				}, {
					name: '审批中'
				}, {
					name: '通过'
				}],
				ScanCode: {
					publicBrandName: '',
					id: '',
					productsNameId: '',
					admissionCertificate: '',
					approvalState: null,
					state: ''
				},
				placeholderStyle: {
					color: '#999'
				},
				showFerrButton: false,
				publicBrandNameEditable: false, // 控制公用品牌名称编辑状态
				productsNameEditable: false, // 控制产品名称编辑状态
				header: $H.getTokenHeader(),
				iamg_tup: '',
				userInfo: null,

				valueProductName: '',
				showNatureBusiness: false,
				natureBusinessList: [],

			}
		},
		computed: {
			fileList() {
				if (Array.isArray(this.ScanCode.admissionCertificate) && this.ScanCode.admissionCertificate.length > 0) {
					return this.ScanCode.admissionCertificate;
				} else {
					return [];
				}
			}
		},
		// onReady() {
		// 	this.$refs.uForm.setRules(this.rules);
		// },
		onLoad(options) {
			const userInfo = uni.getStorageSync('userInfo');
			this.userInfo = userInfo
			const id = options.id;
			this.NewUser(id);
			this.NameList();
		},
		onShow() {
			this.queryApplicationScanCode();
		},
		methods: {
			// 拼接图片地址
			getFullImageUrl(imagePath) {
				return getImageUrl(imagePath);
			},
			downloadQR() {
				// uqrcode为组件的ref名称
				this.$refs.uqrcode.save({
					success: () => {
						uni.showToast({
							icon: 'success',
							title: '保存成功'
						});
					}
				});
			},
			// 用户id
			NewUser(id) {
				$H.get('/brand/user/queryById', {
					id: id
				}, {}).then(res => {
					this.newList = res.result
				}).catch(error => {
					console.log(error)
				});
			},
			// 产品名称下拉
			showNatureBusinessHandler() {
				this.showNatureBusiness = true;
			},
			selectNatureBusiness(e) {
				this.valueProductName = this.natureBusinessList[e[0]].text;
				this.form.productsNameId = this.natureBusinessList[e[0]].id;
			},
			NameList() {
				$H.get('/basisInform/productName/productNameList', {

				}).then((res) => {
					this.natureBusinessList = (res.result || []).map((v) => {
						return {
							text: v.productName,
							id: v.id,
						}
					})
					const target = this.natureBusinessList.find(
						(v) => v.id === this.form.productsNameId
					)
					this.valueProductName = target ? target.text : ''
				})
			},
			// actionClickProductName(index) {
			// 	this.valueProductName = this.actionListCp[index].text;
			// 	this.form.productsNameId = this.actionListCp[index].id;
			// },



			getUploadUrl(url) {
				return $H.getFullUrl('sys/common/upload');
			},

			uploadSuccess(response) {
				if (response.code === 0) {
					uni.showToast({
						title: '图片上传成功',
						icon: 'none'
					});

					// Check if basePhoto already contains an image, replace it with the new one
					if (this.form.basePhoto && this.form.basePhoto.length > 0) {
						this.form.basePhoto[0] = {
							url: response.data,
							message: response.message
						};
					} else {
						// If basePhoto is empty or not defined, initialize it as an array and add the new image
						this.form.basePhoto = [{
							url: response.data,
							message: response.message
						}];
					}

				} else {
					uni.showToast({
						title: response.message || '图片上传失败',
						icon: 'none'
					});
				}
			},
			// 增加
			SubmitApplication(id) {
				let files = this.$refs.uUpload.lists.filter(val => val.progress == 100);

				if (files.length === 0) {
					uni.showToast({
						title: '请上传文件',
						icon: 'none'
					});
					return;
				}

				const requestData = {
					...this.form,
					id: this.id,
					admissionCertificate: files[0].response.message
				};

				$H.post('/agriculture/brandCode/mobile/add', requestData, {})
					.then(res => {
						if (res.code === 200) {
							uni.showToast({
								title: res.message,
								icon: 'none',
							});
							this.queryApplicationScanCode();
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none',
							});
						}
					})
					.catch(error => {
						console.log(error);
					});
			},
			// 查询申请品牌码
			queryApplicationScanCode() {
				$H.get('/agriculture/brandCode/mobile/queryApplicationScanCode', {}, {}).then(res => {
					if (res.code === 500) {
						this.showFerr = true; 
					}
					if (res.result) {
						this.ScanCode = {
							...this.ScanCode,
							...res.result
						};
						this.publicBrandNameEditable = this.ScanCode.state !== 'success'; // 在完成状态下禁止编辑
						this.productsNameEditable = this.ScanCode.state !== 'success'; // 在完成状态下禁止编辑
						if (res.result.admissionCertificate) {
							this.ScanCode.admissionCertificate = [{
								url: this.getFullImageUrl(res.result.admissionCertificate)
							}];
						} else {
							this.ScanCode.admissionCertificate = [];
						}
						this.iamg_tup = res.result.admissionCertificate;
					}
				}).catch(error => {
					console.log(error)
				});
			},

			// 重新提交 
			SubmitAnewAdd() {

				let files = [];
				
				// Get the list of uploaded files
				files = this.$refs.uUpload.lists.filter(val => {
					return val.progress == 100;
				});
				
				// Check if there is a default image
				const hasDefaultImage = this.ScanCode.admissionCertificate && this.ScanCode.admissionCertificate !== '';
				
				// If there is no default image and no uploaded files, prompt to upload a file
				if (!hasDefaultImage && files.length == 0) {
					uni.showToast({
						title: '请上传文件',
						icon: 'none'
					});
					return;
				}
				
				// Get the response.message of the uploaded file, if any
				let responseMessage = '';
				if (files.length > 0 && files[0].response) {
					// Assume response.message is a string, adjust this logic if not
					responseMessage = typeof files[0].response.message === 'string' ? files[0].response.message : '';
				}
				
				// If there is no default image and the upload fails, show an error
				if (!hasDefaultImage && !responseMessage) {
					uni.showToast({
						title: '文件上传失败，请重试',
						icon: 'none'
					});
					return;
				}
				
				// Set admissionCertificate, prioritize the uploaded file, otherwise use the default image
				let admissionCertificate = '';
				if (responseMessage) {
					// Use the uploaded file URL
					admissionCertificate = responseMessage;
				} else if (Array.isArray(this.ScanCode.admissionCertificate)) {
					// If admissionCertificate is an array, use the URL of the first element
					admissionCertificate = this.ScanCode.admissionCertificate[0].url;
				} else {
					// admissionCertificate is already a string
					admissionCertificate = this.ScanCode.admissionCertificate;
				}
				
				const requestData = {
					...this.ScanCode,
					id: this.ScanCode.id,
					admissionCertificate: admissionCertificate
				};
				$H.post('/agriculture/brandCode/mobile/anewAdd', requestData, {}).then(res => {
					if (res.code === 200) {
						uni.showToast({
							title: res.message,
							icon: 'none',
						})
						this.queryApplicationScanCode();
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
						})
					}
				}).catch(error => {
					console.log(error)
				});
			},

			editAndSave() {
				this.showFerrButton = true;
				this.publicBrandNameEditable = true; // 公用品牌名称可编辑
				this.productsNameEditable = true; // 产品名称可编辑
			},
         // 编辑
			SubmitEdit() {
				let files = [];

				// Get the list of uploaded files
				files = this.$refs.uUpload.lists.filter(val => {
					return val.progress == 100;
				});

				// Check if there is a default image
				const hasDefaultImage = this.ScanCode.admissionCertificate && this.ScanCode.admissionCertificate !== '';

				// If there is no default image and no uploaded files, prompt to upload a file
				if (!hasDefaultImage && files.length == 0) {
					uni.showToast({
						title: '请上传文件',
						icon: 'none'
					});
					return;
				}

				// Get the response.message of the uploaded file, if any
				let responseMessage = '';
				if (files.length > 0 && files[0].response) {
					// Assume response.message is a string, adjust this logic if not
					responseMessage = typeof files[0].response.message === 'string' ? files[0].response.message : '';
				}

				// If there is no default image and the upload fails, show an error
				if (!hasDefaultImage && !responseMessage) {
					uni.showToast({
						title: '文件上传失败，请重试',
						icon: 'none'
					});
					return;
				}

				// Set admissionCertificate, prioritize the uploaded file, otherwise use the default image
				let admissionCertificate = '';
				if (responseMessage) {
					// Use the uploaded file URL
					admissionCertificate = responseMessage;
				} else if (Array.isArray(this.ScanCode.admissionCertificate)) {
					// If admissionCertificate is an array, use the URL of the first element
					admissionCertificate = this.ScanCode.admissionCertificate[0].url;
				} else {
					// admissionCertificate is already a string
					admissionCertificate = this.ScanCode.admissionCertificate;
				}

				const requestData = {
					...this.ScanCode,
					id: this.ScanCode.id,
					admissionCertificate: admissionCertificate
				};

				$H.post('/agriculture/brandCode/mobile/edit', requestData, {}).then(res => {
					if (res.code === 200) {
						uni.showToast({
							title: res.message,
							icon: 'none',
						});
						this.showFerrButton = false;
						this.queryApplicationScanCode();
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
						});
					}
				}).catch(error => {
					console.log(error);
				});
			}

		}
	}
</script>

<style>
</style>